//
//  StatusCell.swift
//  XYWeibo
//
//  Created by 常晓璇 on 7/2/15.
//  Copyright © 2015 chang xiaoxuan. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage

/// 图片视图可重用标识符
private let XYPictureReusableIdentifier = "PictureCell"

class StatusCell: UITableViewCell , UICollectionViewDataSource{

    /// 配图视图宽度约束
    var widthCons: NSLayoutConstraint?
    /// 配图视图高度约束
    var heightCons: NSLayoutConstraint?
    
    var status : Status? {
        didSet {
            iconView.sd_setImageWithURL(status?.user?.profileUrl)
            memberIconView.image = status?.user?.mbImage
            vipIconView.image = status?.user?.verifledImage
            
            
            nameLabel.text = status?.user?.name
            timeLabel.text = status?.created_at
            sourceLabel.text = status?.source
            contentLabel.text = status?.text
            
            let size = calcPictureViewSize(status!)
            widthCons?.constant = size.width
            heightCons?.constant = size.height
            
            pictureView.reloadData()
        }
    }
    
    func rowHeight(status:Status) -> CGFloat {
        self.status = status
        
        layoutIfNeeded()
        
        return CGRectGetMaxY(footerView.frame)
    }
    
    // MARK: - CollectionView 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(XYPictureReusableIdentifier, forIndexPath: indexPath) as! StatusPictureCell
        
        cell.imageURL = status!.imageURLs![indexPath.item]
        
        return cell
        
    }
    
    
    private func calcPictureViewSize(status: Status) -> CGSize {
        let count = status.imageURLs?.count ?? 0
        
        if count == 0 {
            return CGSizeZero
        }
        
        if count == 1 {
            // 从缓存拿到并且创建image
            // key 就是 url 的完整字符串 sdwebimage缓存图片文件名是对url的完整字符串md5
            let key = status.imageURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            pictureLayout.itemSize = image.size
            return pictureLayout.itemSize
        
        }
        
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        pictureLayout.itemSize = itemSize
        pictureLayout.minimumInteritemSpacing = margin
        pictureLayout.minimumLineSpacing = margin
        
        if count == 4 {
            let w = itemSize.width * 2 + margin
            return CGSize(width: w, height: w)
        }
        
        let rowCount = 3
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        let h = itemSize.height * CGFloat(row) + CGFloat(row - 1) * margin
        
        return CGSize(width: w, height: h)
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        // 顶部视图
        let screenWidth = UIScreen.mainScreen().bounds.width
        let topView = UIView()
        topView.backgroundColor = UIColor.lightGrayColor()
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopCenter, referView: self, size: CGSize(width: screenWidth, height: 10), offset: CGPointZero)
        
        addSubview(iconView)
        addSubview(nameLabel)
        addSubview(memberIconView)
        addSubview(vipIconView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(contentLabel)
        contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 16
        addSubview(pictureView)
        addSubview(footerView)
        
        // 头像
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 34, height: 34), offset: CGPoint(x: 12, y: 12))
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        memberIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 8))
        timeLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLabel.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        contentLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))
        
        // 配图视图
        let cons = pictureView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: contentLabel, size: CGSize(width: 290, height: 90), offset: CGPoint(x: 0, y: 12))
        // 记录宽高约束
        widthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        heightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
        // 底部视图
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44), offset: CGPoint(x: -12, y: 8))
        preparePictureView()
    }

      //设置配图视图
    private func preparePictureView() {
        pictureView.registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: XYPictureReusableIdentifier)
        pictureView.dataSource = self
        pictureView.backgroundColor = UIColor.lightGrayColor()
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
     // MARK: - 控件的懒加载
    lazy var iconView = UIImageView()
    lazy var nameLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
    lazy var memberIconView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
    lazy var vipIconView: UIImageView = UIImageView(image: UIImage(named: "avatar_grassroot"))
    lazy var timeLabel = UILabel(color: UIColor.orangeColor(), fontSize: 10)
    lazy var sourceLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
    lazy var contentLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15, mutiLines: true)
    
    // 图像视图 - UICollectionView
    lazy var pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView: UICollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 290, height: 90), collectionViewLayout: self.pictureLayout)
    private lazy var footerView: StatusFooterView = StatusFooterView()
}

// 配图cell
private class StatusPictureCell:UICollectionViewCell {
    var imageURL: NSURL?{
        didSet {
            iconView.sd_setImageWithURL(imageURL)
        }
    }
    
    var iconView: UIImageView = UIImageView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(iconView)
        iconView.ff_Fill(self)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// 底部视图
private class StatusFooterView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        addSubview(forwardButton)
        addSubview(commontButton)
        addSubview(likeButton)
        
        ff_HorizontalTile([forwardButton, commontButton, likeButton], insets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///  转发按钮
    lazy var forwardButton: UIButton = UIButton(title: "转发", imageName: "timeline_icon_retweet", fontSize: 12)
    ///  评论按钮
    lazy var commontButton: UIButton = UIButton(title: "评论", imageName: "timeline_icon_comment", fontSize: 12)
    ///  点赞按钮
    lazy var likeButton: UIButton = UIButton(title: "赞", imageName: "timeline_icon_unlike", fontSize: 12)
}
